#!/usr/bin/env python3
# support.py
"""Main wrapper script. This is probably the one you would like to run, if you are not debugging."""

import os, sys, subprocess
sys.path.insert(0, r'/home/george/Projects/ISH') # Change to install path.. like /opt/something
import dialog, sendemail

# Open main window and set up communication with wrapper.
# We need to pipe error messages to /dev/null so they dont mess up our communication with proc
# Down should work with python 3.3 (Wont need to import os, and use /dev/null
#proc = subprocess.Popen(["./whoareu.py"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
with open(os.devnull, 'wb') as fnull:
    proc = subprocess.Popen(["./whoareu.py"], stdout=subprocess.PIPE, stderr = fnull)
stdout = proc.communicate()[0]
stdout_value = stdout.decode("utf-8", "strict")

# Abort wrapper if window is cancelled.
if not (stdout_value):
    sys.exit(0)
else:
    whoareu = (repr(stdout_value))
    list = whoareu.split("\'") # Get rid off ' in the beginning of name.)
    entries = list[1].split("\\n")

#    print (entries[0]) # Name
#    print (entries[1]) # Host
#    print (entries[2]) # Date
#    print (entries[3]) # Mail
#    print (entries[4]) # Issue
# We use globals to communicate with somethingiswrong.py Communicating with the process directly
# are probably better, but this works.
    global issue
    issue = entries[4]
    global to_email
    to_email = entries[3]

    # Ok we've got some user input, so something is going on. Lets log this.
    global log_file
    log_file = dialog.get_logfile()
    with open(log_file, 'w') as f:
        f.write(stdout_value)

    if "Fråga" in (entries[4]):
        '''Let user ask a question'''
        with open(os.devnull, 'wb') as fnull:
            quest = subprocess.Popen(["./ask.py"], stdout=subprocess.PIPE, stderr = fnull)
        stdout_quest = quest.communicate()[0]
        stdout_quest_utf = stdout_quest.decode("utf-8", "strict")

        if not (stdout_quest_utf):
            # Maybe hide whoareu.py and unhide it here?
            sys.exit(0)
        else:
            # Ok, lets append the question to the log file
            with open(log_file, 'a') as f:
                f.write(stdout_quest_utf)

            # and send it...
###            send_result = sendemail.send_email(to_email, issue, log_file)
            sys.exit(0)

    elif "Förslag" in (entries[4]):
        '''Let user add a suggestion'''
        with open(os.devnull, 'wb') as fnull:
            suggest = subprocess.Popen(["./suggest.py"], stdout=subprocess.PIPE, stderr = fnull)
        stdout_suggest = suggest.communicate()[0]
        stdout_suggest_utf = stdout_suggest.decode("utf-8", "strict")

        if not (stdout_suggest_utf):
            # Maybe hide whoareu.py and unhide it here?
            sys.exit(0)
        else:
            # Ok, lets append the suggestion to the log file
            with open(log_file, 'a') as f:
                f.write(stdout_suggest_utf)

            # and send it...
###            send_result = sendemail.send_email(to_email, issue, log_file)
            sys.exit(0)

    elif "Felanmälan" in (entries[4]):
        '''Take dump of user procs and let user restore app or report error'''
        with open(os.devnull, 'wb') as fnull:
            returncode = subprocess.call(["./getuserprocs.py"], stdout=fnull, stderr=fnull)
#        print ("Done with getuserprocs.py") # Debug entry
# Could just incorporate it in the mail? or as an attachement, to make it more interesting ;)

        with open(os.devnull, 'wb') as fnull:
           reset = subprocess.Popen(["./somethingiswrong.py"], stdout=subprocess.PIPE, stderr = fnull)
        stdout_reset = reset.communicate()[0]
        stdout_reset_utf = stdout_reset.decode("utf-8", "strict")
#        print (stdout_reset_utf) # Debug entry
        if not stdout_reset_utf:
            sys.exit(0)

        elif "mkcall" in (stdout_reset_utf):
            with open(os.devnull, 'wb') as fnull:
                error = subprocess.Popen(["./error_report.py"], stdout=subprocess.PIPE, stderr = fnull)
            stdout_error = error.communicate()[0]
            stdout_error_utf = stdout_error.decode("utf-8", "strict")

            if not stdout_error_utf: # Aborted to fill out the error form.
                sys.exit(0)
            else:
                # Ok, lets append the error report to the log file
                with open(log_file, 'a') as f:
                    f.write(stdout_error_utf)

###                send_result = sendemail.send_email(to_email, issue, log_file)
                sys.exit(0)

        # User choosed either "Annat" or "Skrivare"
        elif "otherapp" in (stdout_reset_utf):
            with open(os.devnull, 'wb') as fnull:
                error = subprocess.Popen(["./error.py"], stdout=subprocess.PIPE, stderr = fnull)
            stdout_error = error.communicate()[0]
            stdout_error_utf = stdout_error.decode("utf-8", "strict")

            if not stdout_error_utf: # Aborted to fill out the error form.
                sys.exit(0)
            else:
                # Ok, lets append the error report to the log file
                with open(log_file, 'a') as f:
                    f.write(stdout_error_utf)

                # and send it...
###                send_result = sendemail.send_email(to_email, issue, log_file)
                sys.exit(0)

        # User choosed to reset the app. We want to log app and time to see patterns in errors.
        # Possible choices:
        # OpenOffice Firefox Google Chrome Gimp InDesign Audition Firstclass klienten
        # appname has to be set in both somethingiswrong.glade, somethingiswrong.py and here...
        # Better way to do this?
        elif "OpenOffice" in (stdout_reset_utf):
            with open(log_file, 'a') as f:
                f.write(stdout_reset_utf)

        elif "Firefox" in (stdout_reset_utf):
            with open(log_file, 'a') as f:
                f.write(stdout_reset_utf)

        elif "Google Chrome" in (stdout_reset_utf):
            with open(log_file, 'a') as f:
                f.write(stdout_reset_utf)

        elif "Gimp" in (stdout_reset_utf):
            with open(log_file, 'a') as f:
                f.write(stdout_reset_utf)

        elif "InDesign" in (stdout_reset_utf):
            with open(log_file, 'a') as f:
                f.write(stdout_reset_utf)

        elif "Audition" in (stdout_reset_utf):
            with open(log_file, 'a') as f:
                f.write(stdout_reset_utf)

        elif "Firstclass klienten" in (stdout_reset_utf):
            with open(log_file, 'a') as f:
                f.write(stdout_reset_utf)

        # If down check should be valid  we have to test for appname above.. Needed?
        # Without down we could just do else: with open... above and not have to elif for appname.
        else:
            dialog.error_message("Fick vare sig avbryt, eller ok... Något är fel. Avslutar.")
            sys.exit(1)
    else:
        dialog.error_message("Ingen ärendetyp valdes.. Något är fel. Avslutar.")

